import {
  getSmiListApi,
  getImiListApi,
  getRepReportTemplateListApi,
  addRepReportTemplateApi,
  deleteRepReportTemplateApi,
  modifyRepReportTemplateByEnableApi,
  modifyRepReportTemplateApi,
  getTemplateManagementApi,
  insertRepReportTemplateApi,
  updateRepReportTemplateApi,
  getLabelParametersApi,
  deleteVMApi,
  getVersionApi,
  getLableNameApi
} from '@/services/packetPush.js';
import { message } from 'ant-design-vue';
export default {
  namespaced: true,
  state: {
    firstClassClassificationList: [],
    secondaryClassificationList: [],
    secondaryClassificationListModel: [],
    repReportTemplateLoading: false,
    repReportTemplateList: [],
    paginationOptions: {
      pageNum: 1,
      pageSize: 10,
      total: 0
    },
    // 新增
    addRepReportTemplateLoading: false,
    updateRepReportTemplateLoading: false,
    // 版本管理
    repReportVersionData: {},
    repReportVersionLoading: false,
    normalLabel: [],
    systemLabel: [],
    versionList: [],
    labelTree: [],
    lableNameList: [],
    lableNameListLoading: false
  },
  mutations: {
    setState(state, { key, payload }) {
      state[key] = payload;
    }
  },
  actions: {
    // 一级分类
    async getSmiList({ commit }) {
      const rep = await getSmiListApi();
      const newData = (rep.data ?? []).sort((a, b) => (a?.name ?? 0).localeCompare((b?.name ?? 0)));
      commit('setState', { key: 'firstClassClassificationList', payload: newData });
    },
    // 二级分类
    async getImiList({ commit }, params) {
      const rep = await getImiListApi({ smi: params.smi });
      const newData = (rep.data ?? []).sort((a, b) => (a?.name ?? 0).localeCompare((b?.name ?? 0)));
      if (params.model) {
        commit('setState', { key: 'secondaryClassificationListModel', payload: newData });
      } else {
        commit('setState', { key: 'secondaryClassificationList', payload: newData });
      }
    },
    async getLabelParameters({ commit, state }, params) {
      const rep = await getLabelParametersApi(params);
      const c = [];

      let d = rep.data;
      if (Object.prototype.toString.call(rep.data) === '[object Object]') {
        d = [rep.data];
      }
      const ls = [];
      for (const item of d) {
        if (item['smi']) {
          for (const labelItem of (item.labelName || item.lableName)) {
            ls.push({
              name: labelItem.lableName,
              children: [],
              arrow: true,
              lastP: true,
              lastC: false,
              groupId: labelItem.id,
              pName: `${item['smi']},${item['imi']}`
            });
          }
          c.push({
            name: item['smi'],
            children: [{
              name: item['imi'],
              children: ls,
              arrow: true,
              lastP: false,
              lastC: false,
              pName: `${item['smi']}`
            }],
            arrow: true,
            lastP: false,
            lastC: false,
            pName: ''
          });
        }
      }

      // forLabelTree(rep.data ?? {});
      commit('setState', { key: 'labelTree', payload: c });
    },

    // 删除历史版本
    async deleteVM({ commit }, params) {
      try {
        const rep = await deleteVMApi(params);
        if (rep.code === 200) {
          message.success(rep.message);
          return Promise.resolve(true);
        } else {
          message.error(rep.message);
        }
      } catch (error) {
        message.error('操作失败');
      }
    },

    // 获取模板列表
    async getRepReportTemplateList({ commit, state }, params) {
      commit('setState', { key: 'repReportTemplateLoading', payload: true });
      const { pageNum, pageSize } = state.paginationOptions;
      const apiParams = {
        pageNum,
        pageSize,
        ...params
      };
      const rep = await getRepReportTemplateListApi(apiParams);
      commit('setState', { key: 'repReportTemplateList', payload: rep.data.list });
      commit('setState', { key: 'paginationOptions', payload: { ...state.paginationOptions, total: rep.data.total }});
      commit('setState', { key: 'repReportTemplateLoading', payload: false });
    },

    async insertRepReportTemplate({ commit }, params) {
      commit('setState', { key: 'addRepReportTemplateLoading', payload: true });

      try {
        const rep = await insertRepReportTemplateApi(params);
        if (rep.code === 200) {
          message.success(rep.message);
          return Promise.resolve(true);
        } else {
          message.error(rep.message);
        }
      } catch (error) {
        message.error('操作失败');
      } finally {
        commit('setState', { key: 'addRepReportTemplateLoading', payload: false });
      }
    },
    async updateRepReportTemplate({ commit }, params) {
      commit('setState', { key: 'updateRepReportTemplateLoading', payload: true });

      try {
        const rep = await updateRepReportTemplateApi(params);
        if (rep.code === 200) {
          message.success(rep.message);
          return Promise.resolve(true);
        } else {
          message.error(rep.message);
        }
      } catch (error) {
        message.error('操作失败');
      } finally {
        commit('setState', { key: 'updateRepReportTemplateLoading', payload: false });
      }
    },
    async addRepReportTemplate({ commit }, params) {
      commit('setState', { key: 'addRepReportTemplateLoading', payload: true });

      try {
        const rep = await addRepReportTemplateApi(params);
        if (rep.data === '成功') {
          message.success(rep.message);
          return Promise.resolve(true);
        } else {
          message.error(rep.message);
        }
      } catch (error) {
        message.error('操作失败');
      } finally {
        commit('setState', { key: 'addRepReportTemplateLoading', payload: false });
      }
    },
    // 删除
    async deleteRepReportTemplate({ commit }, params) {
      try {
        const rep = await deleteRepReportTemplateApi(params);
        if (rep.data === '成功') {
          message.success(rep.message);
          return Promise.resolve(true);
        } else {
          message.error(rep.message);
        }
      } catch (error) {
        message.error('操作失败');
      }
    },
    // 切换状态
    async modifyRepReportTemplateByEnable({ commit }, params) {
      try {
        const rep = await modifyRepReportTemplateByEnableApi(params);
        if (rep.data === '成功') {
          message.success(rep.message);
          return Promise.resolve(true);
        } else {
          message.error(rep.message);
        }
      } catch (error) {
        message.error('操作失败');
      }
    },
    // 修改
    async modifyRepReportTemplate({ commit }, params) {
      commit('setState', { key: 'addRepReportTemplateLoading', payload: true });
      try {
        const rep = await modifyRepReportTemplateApi(params);
        if (rep.data === '成功') {
          message.success(rep.message);
          return Promise.resolve(true);
        } else {
          message.error(rep.message);
        }
      } catch (error) {
        message.error('操作失败');
      } finally {
        commit('setState', { key: 'addRepReportTemplateLoading', payload: false });
      }
    },
    // 修改
    async getTemplateManagement({ commit }, params) {
      commit('setState', { key: 'repReportVersionLoading', payload: true });
      const rep = await getTemplateManagementApi({ ...params });
      let data = [];
      if (rep.data) {
        if (rep.data.push) {
          data = [...rep.data];
        } else {
          data = [rep.data];
        }
      }

      data.forEach(item => {
        if (!item.templateDetails) {
          item.templateDetails = [];
        }
      });

      if (typeof data?.[0]?.templateDetails?.[0] !== 'string') {
        data?.[0]?.templateDetails.forEach(item => {
          if (item.length) {
            item['width'] = item.length;
          }
        });
      }

      commit('setState', { key: 'repReportVersionData', payload: data });
      commit('setState', { key: 'repReportVersionLoading', payload: false });
    },

    // 根据名称获取版本信息
    async getVersion({ commit, state }, params) {
      const rep = await getVersionApi(params);
      commit('setState', { key: 'versionList', payload: rep.data });
    },
    // 根据名称获取版本信息
    async getLableName({ commit, state }, params) {
      commit('setState', { key: 'lableNameListLoading', payload: true });
      try {
        const rep = await getLableNameApi(params);
        commit('setState', { key: 'lableNameList', payload: rep.data });
      } finally {
        commit('setState', { key: 'lableNameListLoading', payload: false });
      }
    }

  }
};
